;; Markdown 配置

(require 'init-package)

;; eln 会使markdown-mode 无法正常使用 imenu, 下面这行禁止Emacs eln "markdown-mode"
(setq native-comp-deferred-compilation-deny-list '("markdown-mode\\.el$"))

(when (maybe-require-package 'markdown-mode)
      (autoload 'markdown-mode "markdown-mode"
        "Major mode for editing Markdown files" t)
      (add-to-list 'auto-mode-alist
                   '("\\.\\(?:md\\|markdown\\|mkd\\|mdown\\|mkdn\\|mdwn\\)\\'" . markdown-mode))

      (autoload 'gfm-mode "markdown-mode"
        "Major mode for editing GitHub Flavored Markdown files" t)
      (add-to-list 'auto-mode-alist '("README\\.md\\'" . gfm-mode))

      (add-hook 'markdown-mode-hook #'my/setup-markdown)
      (add-hook 'gfm-mode-hook #'my/setup-markdown)
      )

(defun my/setup-markdown ()
  ;; 将插入样式绑定到 C-，默认是 C-c C-s比较难按
  (define-key markdown-mode-map (kbd "C-,") markdown-mode-style-map)

  (define-key markdown-mode-map (kbd "C-c C-e") #'markdown-do)
  (define-key markdown-mode-map (kbd "C-c p") #'markdown-previous-link)
  (define-key markdown-mode-map (kbd "C-c n") #'markdown-next-link)

  (define-key markdown-mode-map (kbd "M-n") 'scroll-up)
  (define-key markdown-mode-map (kbd "M-p") 'scroll-down)
  ;; (define-key markdown-mode-map (kbd "C-j") (lambda ()
  ;;                                             (interactive)
  ;;                                             (move-end-of-line 1)
  ;;                                             (insert "  \n")))
  ;; (define-key markdown-mode-map (kbd "SPC") 'my/insert-whitespace)
  (define-key markdown-mode-map (kbd "C-j") 'my/insert-whitespace)
  (define-key markdown-mode-map (kbd "<backspace>") 'backward-delete-char-untabify)
  ;;(define-key markdown-mode-map (kbd "C-S-<return>") (kbd "<home><return><up>"))

  (custom-set-faces
   '(markdown-code-face ((t (:inherit font-lock-doc-face))))
   '(markdown-inline-code-face ((t (:inherit markdown-code-face))))
   '(markdown-table-face ((t (:inherit markdown-code-face)))))

  (custom-set-variables
   '(markdown-code-lang-modes
     '(("elisp" . emacs-lisp-mode)
       ("sqlite" . sql-mode)
       ("C" . c-mode)
       ("cpp" . c++-mode)
       ("C++" . c++-mode)
       ("shell" . sh-mode)
       ("bash" . sh-mode)
       ("csharp" . csharp-mode)))))


(defun my/insert-whitespace ()
  "如果是在行的开头则插入全角空格，否则插入半角空格"
  (interactive)
  (let* ((begin (line-beginning-position))
         (end (point))
         (header (when (< begin end)
                   (buffer-substring begin end))))
    (if (= begin end)
        (insert "　")
      (if (string-match "^　*$" header)
          (insert "　")
        (insert " ")))))

(provide 'init-markdown)
